package com.lvcoding.authserver.config;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 授权服务器
 */
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final ClientDetailsService clientDetailsService;

    private final AuthenticationManager authenticationManager;

    private final TokenStore tokenStore;

    // private final JwtAccessTokenConverter jwtAccessTokenConverter;

    private final DataSource dataSource;

    private final UserDetailsService userDetailsService;

    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices tokenService = new DefaultTokenServices();
        tokenService.setTokenStore(tokenStore);
        tokenService.setClientDetailsService(clientDetailsService);
        tokenService.setSupportRefreshToken(true);
        tokenService.setAccessTokenValiditySeconds(60 * 60 * 2);
        tokenService.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);



        // TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); // token增强链
        // List<TokenEnhancer> enhancers = new ArrayList<>();
        // enhancers.add(jwtAccessTokenConverter);
        // tokenEnhancerChain.setTokenEnhancers(enhancers);
        //
        // tokenService.setTokenEnhancer(tokenEnhancerChain); // jwt令牌必须

        return tokenService;
    }

    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        // return new InMemoryAuthorizationCodeServices();
        return new JdbcAuthorizationCodeServices(dataSource); // 基于JDBC存储code
    }

    /**
     * 配置令牌端点的安全约束
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()") // 允许资源服务器调用授权服务器的 /oauth/check_token方法
                .allowFormAuthenticationForClients(); // 允许客户端进行表单登录
    }

    /**
     * 配置客户端信息
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // clients.inMemory()
        //         .withClient("app")
        //         .secret(passwordEncoder.encode("123"))
        //         .resourceIds("res1")
        //         .scopes("all")
        //         .redirectUris("http://localhost:18082/index.html")
        //         .authorizedGrantTypes("authorization_code", "password", "implicit", "client_credentials", "refresh_token");

        clients.withClientDetails(new JdbcClientDetailsService(dataSource)); // 基于JDBC存储客户端
    }

    /**
     * 配置令牌(token)的访问端点和令牌(token)服务(tokenServices)
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authorizationCodeServices(authorizationCodeServices())
                .allowedTokenEndpointRequestMethods(HttpMethod.POST)
                .authenticationManager(authenticationManager) // 密码模式必须有
                .tokenServices(tokenServices());
    }


}
